<template>
  <el-result
    icon="warning"
    title="残课题清单未生成"
    v-if="
      !(formData && formData.residuals && formData.residuals.length > 0) &&
      !loading
    "
  >
    <template #extra>
      <el-button type="primary" @click="createResiduals">立即生成</el-button>
    </template>
  </el-result>
  <div v-else id="main">
    <el-skeleton :rows="5" animated v-if="loading" />
    <div v-else>
      <div class="fixed-button">
        <div style="display: flex; align-items: center">
          <el-text tag="b"
            >{{ formData.itemId }}/{{ formData.itemRevisionId }} -
            {{ formData.objectName }} [残课题清单]
          </el-text>
        </div>
        <div style="display: flex; flex-direction: row; justify-self: start">
          <div style="margin-right: 30px">
            <el-button
              type="primary"
              @click="createResiduals(true)"
              :loading="loading"
              :disabled="loading || formReadOnly"
              >重新生成</el-button
            >
          </div>
          <div style="margin-right: 30px">
            <el-button type="primary" @click="exportPDF" :loading="loading"
              >导出</el-button
            >
          </div>
        </div>
      </div>
      <el-table
        :data="formData.residuals"
        :key="tableKey"
        style="width: auto; margin-top: 70px"
        highlight-current-row
        border
        table-layout="auto"
      >
        <el-table-column
          type="index"
          label="序号"
          width="60"
          show-overflow-tooltip
        />
        <el-table-column prop="subject" label="主题" width="180" />
        <el-table-column prop="content" label="内容" width="250" />
        <el-table-column prop="reason" label="指摘要因" width="90" />
        <el-table-column
          prop="introducer_name"
          label="提出者"
          width="130"
          show-overflow-tooltip
        />
        <el-table-column
          prop="replier_name"
          label="回复者"
          width="130"
          show-overflow-tooltip
        />
        <el-table-column
          prop="judge"
          label="指摘判断"
          width="90"
          show-overflow-tooltip
        />
        <el-table-column prop="measure" label="指摘对策" width="150" />
        <el-table-column
          prop="plan_completion_node"
          label="计划完成节点"
          width="120"
        />
        <el-table-column
          prop="progress"
          label="对策状况"
          width="100"
          show-overflow-tooltip
        />
        <el-table-column
          prop="confirmation"
          label="对策确认"
          width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-tag
              v-if="scope.row.confirmation"
              :type="scope.row.confirmation === 'OK' ? 'success' : 'danger'"
              disable-transitions
              >{{ scope.row.confirmation }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template #default="{ $index }">
            <el-button
              link
              type="primary"
              size="small"
              @click="openBlameView($index)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <el-drawer
    v-model="isShowBlameView"
    title="指摘详情"
    direction="rtl"
    class="demo-drawer"
    :show-close="true"
    size="650px"
  >
    <template #header="{ titleId, titleClass }">
      <h4 :id="titleId" :class="titleClass">指摘详情</h4>
    </template>
    <BlameView
      ref="blameViewRef"
      :userId="userId"
      :formReadOnly="true"
      :formData="displayBlameFormData"
      lock-scroll
    ></BlameView>
  </el-drawer>
</template>
<script lang="ts" setup>
import {
  reactive,
  ref,
  onMounted,
  getCurrentInstance,
  toRefs,
  nextTick,
  watch,
} from "vue";
import { useRouter } from "vue-router";
import BlameView from "./BlameView.vue";
import { ElMessage } from "element-plus";
import { htmlToPDF } from "@/utils/html2pdf";

const instance = getCurrentInstance();
const { $http } = instance?.appContext.config.globalProperties as any;
const router = useRouter();
const loading = ref(false);
const formReadOnly = ref(true);
const blameViewRef = ref<any>(null);
const inited = ref(false);
const uid = ref();
// const datas = ref<any>([]);
const formData = ref();
const tableKey = ref(0);
const blameIndex = ref(-1);
const isShowBlameView = ref(false);
const displayBlameFormData: { [key: string]: any } = ref({});
const userId = ref();

onMounted(() => {
  uid.value = router.currentRoute.value.query.uid as string;
  userId.value = router.currentRoute.value.query.userId as string;
  let rdstr = router.currentRoute.value.query.readonly as string;
  let checkoutUserId = router.currentRoute.value.query.checkUserId as string;

  if (checkoutUserId) {
    formReadOnly.value = checkoutUserId !== userId.value;
  } else {
    formReadOnly.value = "false" !== rdstr;
  }

  loadData();
  (window as any).setFormReadOnly = setFormReadOnly;
});

const loadData = () => {
  loading.value = true;
  $http
    .get("/getResiduals?residualsDocUid=" + uid.value)
    .then((response: { data: any }) => {
      console.log("残课题清单查询结果：", response.data);
      formData.value = response.data;
      loading.value = false;
      inited.value = true;
      console.log("残课题清单查询结果：", formData.value);
    })
    .catch((error: any) => {
      console.log(error);
      inited.value = true;
      loading.value = false;
      ElMessage({
        type: "error",
        message: error,
      });
    });
};

const createResiduals = async (isCover: boolean) => {
  try {
    loading.value = true;
    let coverStr = isCover ? "true" : "false";
    let response = await $http.get(
      "/createResiduals?residualsDocUid=" + uid.value + "&isCover=" + coverStr
    );
    if ("error" === response.data.status) {
      ElMessage({
        type: "error",
        message: response.data.msg,
      });
    } else {
      loadData();
    }
  } catch (error) {
    ElMessage({
      type: "error",
      message: error,
    });
  } finally {
    loading.value = false;
  }
  // console.log(">>>", datas.value);
};

const setFormReadOnly = (isReadOnly: boolean) => {
  formReadOnly.value = isReadOnly;
};

const openBlameView = (index: number) => {
  console.log("显示第 " + index + " 个数据");
  //console.log(blameFormDatas.value[index]);
  isShowBlameView.value = true;
  blameIndex.value = index;
  // displayBlameFormData.value = blameFormDatas.value[index];
  nextTick(() => {
    displayBlameFormData.value = {};
    for (const key in formData.value.residuals[index]) {
      displayBlameFormData.value[key] = formData.value.residuals[index][key];
    }
    // let introducer_id = displayBlameFormData.value.introducer_id;
    // //只有提出人和当前文档访问者相同时，才有编辑权限
    // let ediatble = introducer_id == userId.value;
    blameViewRef.value.setFormData(displayBlameFormData.value, userId.value);
  });
};

const exportPDF = async () => {
  htmlToPDF("main", "设计品质确认表");
};

const handleOpen = (key: string, keyPath: string[]) => {
  console.log(key, keyPath);
};
const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath);
};

const onBlameDataChange = (subject: string, formData: any) => {
  console.log("接收到子页数据：", formData);
  //blameForms[subject] = formData;
  setDirty(true);
};

const setDirty = (isDirty: boolean) => {
  console.log("是否修改 ==> " + isDirty);
  let win = window as any;
  if (win.java && win.java.setDirty) {
    win.java.setDirty(isDirty);
  }
};
</script>
<style>
.text-left {
  text-align: left;
  width: 15px;
}
.fixed-button {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  padding: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 999;
  display: flex;
  justify-content: space-between;
}
.form-content {
  /* 确保表单内容不被保存按钮遮挡 */
  /* margin-top: 70px; */
  margin-top: 10px;
}
.read-only-input .el-input__inner {
  background-color: #f5f5f5;
}
.read-only-input .el-input__wrapper {
  background-color: #f5f5f5;
}
.el-collapse .el-collapse-item__header {
  font-size: 16px;
  font-weight: bold;
}
</style>
